package com.singzi.leetcode.jianzhiOffer;

import java.util.ArrayList;
import java.util.List;

public class T00571 {
}
class Solution00571 {
    public int[] spiralOrder(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int []ans = new int[m*n];
        addNum(matrix, ans, 0, 0, m, n, 0, 1, 0);
        return ans;
    }
    public void addNum(int[][] matrix, int[]ans, int i, int j, int m, int n, int index,int d,int range){
        if(index == m*n) return;
        if(d == 1){
            ans[index] = matrix[i][j];
            if(j+1 < n && j < n-range) {
                addNum(matrix, ans, i, j+1, m, n, index+1, 1,range);
            }else{
                addNum(matrix, ans, i+1, j, m, n, index+1, 2,range);
            }
        }
        if(d == 2){
            ans[index] = matrix[i][j];
            if(i+1<m && i+1<m-range) {
                addNum(matrix, ans, i+1, j, m, n, index+1, 2,range);
            }else{
                addNum(matrix, ans, i, j-1, m, n, index+1, 3,range);
            }
        }
        if(d == 3){
            ans[index] = matrix[i][j];
            if(j > 0 && j > range) {
                addNum(matrix, ans, i, j-1, m, n, index+1, 3,range);
            }else{
                addNum(matrix, ans, i-1, j, m, n, index+1, 4,range);
            }
        }
        if(d == 4){
            ans[index] = matrix[i][j];
            if(i > 0&& j > range) {
                addNum(matrix, ans, i-1, j, m, n, index+1, 4,range);
            }else{
                addNum(matrix, ans, i, j+1, m, n, index+1, 1,range+1);
            }
        }


    }
}